/**
 * @file
 * @author Ivan Babushkin (jogrms@gmail.com)
 * @date 13.06.2010
 */

#include <webview.h>
#include <QtWebKit/QWebView>
#include <QtWebKit/QWebPage>
#include <QtWebKit/QWebFrame>
#include <QDebug>
#include <qorangeapp.h>
#include <QKeyEvent>
#include <QWheelEvent>
#include <qodefault.h>
#include <mainwindow.h>

WebView::WebView(struct QOSettings *settings, QWidget *parent) :QWebView(parent) {
	connect(this, SIGNAL(loadStarted()), static_cast<MainWindow*>(parent),
			SLOT(loadStarted()));
	connect(this, SIGNAL(loadProgress(int)), static_cast<MainWindow*>(parent),
			SLOT(loadProgress(int)));
	connect(this, SIGNAL(loadFinished(bool)), static_cast<MainWindow*>(parent),
			SLOT(loadFinished(bool)));
	connect(this, SIGNAL(loadProgress(int)), this, SLOT(setProgress(int)));

	page()->mainFrame()->setScrollBarPolicy(Qt::Horizontal, settings->webViewHScroll);
	page()->mainFrame()->setScrollBarPolicy(Qt::Vertical, settings->webViewVScroll);
	pageAction(QWebPage::OpenLinkInNewWindow)->setText("Open Link in New Tab");
}

WebView::~WebView() {
}

WebView* WebView::createWindow(QWebPage::WebWindowType type) {
	return static_cast<QOrangeApp*>(QOrangeApp::instance())->createNewTab();
}

void WebView::keyPressEvent(QKeyEvent *event) {
	QWebView::keyPressEvent(event);
	//event->ignore();
/*	if (event->isAccepted()) {
		qDebug() << "test";
		return;
	}
	else {
		switch (event->key()) {
			case Qt::Key_Up:
				page()->mainFrame()->scroll(0, -15);
				break;

			case Qt::Key_Down:
				page()->mainFrame()->scroll(0, 15);
				break;

			case Qt::Key_Left:
				page()->mainFrame()->scroll(-15, 0);
				break;

			case Qt::Key_Right:
				page()->mainFrame()->scroll(15, 0);
				break;
		}
	}*/
}

void WebView::wheelEvent(QWheelEvent *event) {
	QWebView::wheelEvent(event);
//	if (event->isAccepted()) {
//		return;
//	}
	if (event->orientation() == Qt::Vertical) {
		if (page()->frameAt(event->pos())->scrollBarGeometry(Qt::Vertical).isEmpty()) {
			page()->mainFrame()->scroll(0, -event->delta() / 2);
		}
	}
	else {
		if (page()->frameAt(event->pos())->scrollBarGeometry(Qt::Horizontal).isEmpty()) {
			page()->mainFrame()->scroll(-event->delta() / 2, 0);
		}
	}
	event->accept();
}

int WebView::getProgress() {
	return progress;
}

void WebView::setProgress(int progress) {
	this->progress = progress;
}
